/*
 * Copyright 2009 Cedric Priscal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package android_serialport_api;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.LinkedBlockingQueue;

import android.util.Log;

public class SerialPort {

	private static final String TAG = "SerialPort";
	private LinkedBlockingQueue<byte[]> requestQueen = new LinkedBlockingQueue<byte[]>();
	private final Object lock = new Object();
	/** 连接成功 **/
	public final int CONNECTSUCCESS = 1;
	/** 连接失败 **/
	public final int DISCONNECT = 2;
	private int state = DISCONNECT;
	private FileDescriptor mFd;
	private FileInputStream mFileInputStream;
	private FileOutputStream mFileOutputStream;

	private Thread conn = null;
	private Thread send = null;
	private Thread rec = null;
	SerialReceiveListener listener = null;

	public void setListener(SerialReceiveListener listener) {
		this.listener = listener;
	}

	public SerialPort(File device, int baudrate, int flags)
			throws SecurityException, IOException {

		/* Check access permission */
		if (!device.canRead() || !device.canWrite()) {
			try {
				/* Missing read/write permission, trying to chmod the file */
				Process su;
				su = Runtime.getRuntime().exec("/system/bin/su");
				String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
						+ "exit\n";
				su.getOutputStream().write(cmd.getBytes());
				if ((su.waitFor() != 0) || !device.canRead()
						|| !device.canWrite()) {
					throw new SecurityException();
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new SecurityException();
			}
		}

		mFd = open(device.getAbsolutePath(), baudrate, flags);
		if (mFd == null) {
			Log.e(TAG, "native open returns null");
			throw new IOException();
		}
		mFileInputStream = new FileInputStream(mFd);
		mFileOutputStream = new FileOutputStream(mFd);
		state = CONNECTSUCCESS;

		send = new Thread(new Send());

		rec = new Thread(new Rec());
		send.start();
		rec.start();
	}

	public OutputStream getOutputStream() {
		// TODO Auto-generated method stub
		return mFileOutputStream;
	}

	public InputStream getInputStream() {
		// TODO Auto-generated method stub
		return mFileInputStream;
	}

	// JNI
	private native static FileDescriptor open(String path, int baudrate,
			int flags);

	public native void close();

	static {
		System.loadLibrary("serial_port");
	}

	private class Send implements Runnable {
		public void run() {
			try {
				while (state == CONNECTSUCCESS) {
					byte[] item = null;
					while (null != (item = requestQueen.poll())) {
						if (item != null) {
							mFileOutputStream.write(item);
							mFileOutputStream.flush();
						}
						item = null;
					}
					synchronized (lock) {
						lock.wait();
					}
				}
			} catch (Exception e1) {
				e1.printStackTrace();

				// Connection();
			}

		}
	}

	public void SendData(byte[] msg) {
		requestQueen.add(msg);
		synchronized (lock) {
			lock.notifyAll();
		}

	}

	private class Rec implements Runnable {
		byte[] buffer = new byte[1024];
		String SerialBuf = "";

		@Override
		public void run() {
			while (true) {

				try {

					int size = mFileInputStream.read(buffer);
					if (size > 0) {
						for (int i = 0; i < size; i++) {
							if (buffer[i] == 0X13) {
								buffer[i] = 0X03;
							}
						}
						SerialBuf = SerialBuf
								+ new String(buffer, 0, size, "UTF-8");
						while (true) {
							int StartPos = SerialBuf.indexOf(getHex3());
							if (StartPos != -1) {
								String tempStr = SerialBuf.substring(0,
										StartPos + 1);
								if (listener != null) {
									listener.serialReceive(tempStr);					
								}
								SerialBuf = SerialBuf.substring(StartPos + 1);
							} else {
								break;
							}

						}

					}
				} catch (Exception e) {
				}
			}
		}
	}

	public String getHex3() {
		String result = "";
		try {
			byte[] bu = new byte[1];
			bu[0] = 0X03;
			result = new String(bu, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}
